package com.example.newhbsj;

import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.ab.activity.AbActivity;
import com.ab.fragment.AbDialogFragment.AbDialogOnLoadListener;
import com.ab.fragment.AbLoadDialogFragment;
import com.ab.http.AbHttpUtil;
import com.ab.http.AbStringHttpResponseListener;
import com.ab.util.AbDialogUtil;
import com.ab.view.pullview.AbPullToRefreshView;
import com.ab.view.pullview.AbPullToRefreshView.OnFooterLoadListener;
import com.ab.view.pullview.AbPullToRefreshView.OnHeaderRefreshListener;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.model.LatLng;
import com.example.adapter.MainAdapters;
import com.example.bean.Listitem;

import com.example.view.ExpandTabView;

import com.example.view.PopMenu;
import com.example.view.ViewMiddle;
import com.example.view.ViewRight;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;

import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.RelativeLayout;
import android.widget.Toast;

import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends AbActivity implements OnClickListener,
		com.example.view.PopMenu.OnItemClickListener, OnHeaderRefreshListener,
		OnFooterLoadListener {
	MapView mMapView = null;

	private AbPullToRefreshView refreshview;

	private ExpandTabView expandTabView;
	private AbHttpUtil mAbHttpUtil = null;
	ArrayList<LatLng> Markerlist = new ArrayList<LatLng>();
	private ArrayList<View> mViewArray = new ArrayList<View>();
	public static ArrayList<Listitem> title = new ArrayList<Listitem>();
	private PopMenu popMenu;
	private ViewMiddle viewMiddle;
	private ViewRight viewRight;
	private ListView listview;
	private LinearLayout juli;
	private ImageButton erbaimi, wubaimi, qianmi, erqianmi, wuqianmi, wanmi;
	// private RelativeLayout bar;
	private Button distance;
	private ImageButton exit;
	private ImageButton person;
	private ImageButton map;
	private ImageButton list;
	public static ArrayList<String> list1 = new ArrayList<String>();
	public static ArrayList<String> list_values = new ArrayList<String>();

	MainAdapters adapter;
	AbHttpUtil abhttputil = null;
	String str = "";
	String detail1;
	String detail;
	int count = 0;
	String distant;
	String kid = "0";
	String type = "";
	int page = 1;
	String pageindex = page + "";
	String allshowText;
	private AbLoadDialogFragment mDialogFragment = null;
	// 初始化地图
	BaiduMap mBaiduMap;
	LocationClient mLocationClient;
	BDLocationListener myListener = new MyLocationListener();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		abhttputil = AbHttpUtil.getInstance(this);
		abhttputil.setTimeout(1000);
		// 加载地图
		SDKInitializer.initialize(getApplicationContext());

		setContentView(R.layout.activity_main);
		mMapView = (MapView) findViewById(R.id.bmapView);
		exit = (ImageButton) findViewById(R.id.exit);
		person = (ImageButton) findViewById(R.id.person);
		map = (ImageButton) findViewById(R.id.map);
		person = (ImageButton) findViewById(R.id.person);
		list = (ImageButton) findViewById(R.id.list);
		listview = (ListView) findViewById(R.id.detail);
		distance = (Button) findViewById(R.id.distance);
		juli = (LinearLayout) findViewById(R.id.juli);
		// bar = (RelativeLayout) findViewById(R.id.bar);
		erbaimi = (ImageButton) findViewById(R.id.erbaimi);
		wubaimi = (ImageButton) findViewById(R.id.wubaimi);
		qianmi = (ImageButton) findViewById(R.id.qianmi);
		erqianmi = (ImageButton) findViewById(R.id.erqianmi);
		wuqianmi = (ImageButton) findViewById(R.id.wuqianmi);
		wanmi = (ImageButton) findViewById(R.id.yiwanmi);
		refreshview = (AbPullToRefreshView) findViewById(R.id.mPullRefreshView);

		refreshview.setOnFooterLoadListener(this);
		refreshview.setOnHeaderRefreshListener(this);

		distant = "500";

		mMapView.setOnClickListener(this);
		exit.setOnClickListener(this);
		person.setOnClickListener(this);
		map.setOnClickListener(this);
		list.setOnClickListener(this);
		distance.setOnClickListener(this);
		erbaimi.setOnClickListener(this);
		wubaimi.setOnClickListener(this);
		qianmi.setOnClickListener(this);
		erqianmi.setOnClickListener(this);
		wuqianmi.setOnClickListener(this);
		wanmi.setOnClickListener(this);

		mDialogFragment = AbDialogUtil.showLoadDialog(this, R.drawable.ic_load,
				"查询中,请等一小会");
		mDialogFragment.setAbDialogOnLoadListener(new AbDialogOnLoadListener() {

			@Override
			public void onLoad() {
				// TODO Auto-generated method stub
				newthread(kid, distant);
				init("/api/HotKeyword");
				initLocation();
				menu();

			}
		});

		refreshview.getHeaderView().setHeaderProgressBarDrawable(
				this.getResources().getDrawable(R.drawable.progress_circular));
		refreshview.getFooterView().setFooterProgressBarDrawable(
				this.getResources().getDrawable(R.drawable.progress_circular));

		listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// TODO Auto-generated method stub
				Intent i = new Intent(MainActivity.this, TestActivity.class);
				i.putExtra("a", position);
				// Toast.makeText(MainActivity.this, position,
				// Toast.LENGTH_SHORT).show();
				startActivity(i);
				finish();
			}
		});

		//

	}

	Handler handle = new Handler();

	// 个人中心
	private void menu() {
		popMenu = new PopMenu(this);
		popMenu.addItems(new String[] { "二维码", "我的资料", "商家代金券", "货比三家优惠券", "登陆" });
		popMenu.setOnItemClickListener(this);
	}

	// 加載第三方控件
	private void init(String url) {
		mAbHttpUtil = AbHttpUtil.getInstance(this);
		mAbHttpUtil.setTimeout(10000);
		detail = "http://www2.huobi3j.com" + url;
		mAbHttpUtil.get(detail, new AbStringHttpResponseListener() {

			@Override
			public void onSuccess(int arg0, String arg1) {
				// TODO Auto-generated method stub
				try {
					JSONArray array = new JSONArray(arg1);
					for (int i = 0; i < array.length(); i++) {
						JSONObject object = (JSONObject) array.get(i);
						String name = (String) object.get("name");
						list1.add(name);
						String values = object.getString("values");
						list_values.add(values);
					}
					initView();
					initVaule();
					initListener();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
				}
			}

			@Override
			public void onFailure(int arg0, String arg1, Throwable arg2) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onFinish() {
				// TODO Auto-generated method stub
			}

			@Override
			public void onStart() {
				// TODO Auto-generated method stub
			}
		});
	}

	// 点击类型获取listview信息
	public void newthread(final String kid, String distance) {
		title.clear();

		String detail1 = "http://www.huobi3j.com/product/searchproduct?kid="
				+ kid + "&lat=23.01867&lng=113.13816&radius=" + distant
				+ "&sort=Price&typeid=&priceid=&sizeid=&pageindex=1%22";

		abhttputil.get(detail1, new AbStringHttpResponseListener() {

			@Override
			public void onStart() {
				// TODO Auto-generated method stub
			}

			@Override
			public void onFinish() {
				// TODO Auto-generated method stub
			}

			@Override
			public void onFailure(int arg0, String arg1, Throwable arg2) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onSuccess(int arg0, String arg1) {
				// TODO Auto-generated method stub
				try {
					JSONObject object = new JSONObject(arg1);
					String contents = object.getString("contents");
					JSONArray array = new JSONArray(contents);
					for (int i = 0; i < array.length(); i++) {
						Listitem item = new Listitem();
						JSONObject detail = (JSONObject) array.get(i);
						String Name = detail.getString("title");
						String tags = detail.getString("tags");
						String Phone = detail.getString("Phone");
						String Price = detail.getString("Price");
						// String Address = detail.getString("address");
						String distance = detail.getString("distance");
						String loc = detail.getString("location");
						item.setName(Name);
						item.setPrices(Price);
						item.setPhone(Phone);
						item.setDistance(distance);
						item.setTags(tags);
						item.setLocation(loc);
						title.add(item);
					}
					set(title);
					adapter = new MainAdapters(MainActivity.this, title);
					listview.setAdapter(adapter);
					// bar.setVisibility(View.GONE);
					mDialogFragment.loadFinish();

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

	}

	// 添加覆盖物
	public void set(ArrayList<Listitem> title) {
		mBaiduMap.clear();
		for (int i = 0; i < title.size(); i++) {
			String str = title.get(i).getLocation();
			double cLon = Double
					.parseDouble(str.substring(1, str.indexOf(",")));
			double cLat = Double.parseDouble(str.substring(
					str.indexOf(",") + 1, str.length() - 1));
			LatLng point = new LatLng(cLat, cLon);
			OverlayOptions options = new MarkerOptions()
					.position(point)
					.icon(BitmapDescriptorFactory
							.fromResource(R.drawable.nav_turn_via_1))
					.zIndex(17).draggable(false);
			mBaiduMap.addOverlay(options);
			Marker marker = (Marker) mBaiduMap.addOverlay(options);
			Bundle bundle = new Bundle();
			bundle.putInt("position", i);

			marker.setExtraInfo(bundle);

		}

		// 覆盖物点击响应事件
		mBaiduMap.setOnMarkerClickListener(new OnMarkerClickListener() {

			@Override
			public boolean onMarkerClick(Marker arg0) {
				Intent i = new Intent(MainActivity.this, TestActivity.class);
				Bundle bundle = new Bundle();
				LatLng v = arg0.getPosition();
				Log.d("q", v.latitude + "");
				Markerlist.add(v);
				bundle.putSerializable("Marker", Markerlist);
				i.putExtras(bundle);
				startActivity(i);

				return false;
			}
		});

	}

	// 定位
	private void initLocation() {
		mBaiduMap = mMapView.getMap();
		// 开启定位图层
		mBaiduMap.setMyLocationEnabled(true);
		// 初始化LocationClient类
		mLocationClient = new LocationClient(this); // 声明LocationClient类
		mLocationClient.registerLocationListener(myListener); // 注册监听函数
		// 定位初始化 //配置定位SDK参数
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);// 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.setScanSpan(1000);

		mLocationClient.setLocOption(option);
		mLocationClient.start();// 开启定位
	}

	boolean isFirstLoc = true;// 是否首次定位

	// 实现BDLocationListener接口，监听定位
	public class MyLocationListener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// Receive Location
			// Receive Location
			// map view 销毁后不在处理新接收的位置
			if (location == null || mMapView == null)
				return;
			double cLat = 23.01867;
			double cLon = 113.13816;

			// double cLat = location.getLatitude();
			// double cLon = location.getLongitude();
			// 设定经纬度，方向信息
			MyLocationData locData = new MyLocationData.Builder().accuracy(200)
			// 此处设置开发者获取到的方向信息，顺时针0-360
			// .direction(100)
					.latitude(cLat).longitude(cLon).build();
			// //设置定位数据
			mBaiduMap.setMyLocationData(locData);
			if (isFirstLoc) {
				isFirstLoc = false;
				LatLng ll = new LatLng(cLat, cLon);
				// 定义地图状态
				MapStatus mMapStatus = new MapStatus.Builder().target(ll)
						.zoom(17).build();
				// 定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
				MapStatusUpdate u = MapStatusUpdateFactory
						.newMapStatus(mMapStatus);
				// 改变地图状态
				mBaiduMap.animateMapStatus(u);

			}
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mMapView.onDestroy();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		mMapView.onPause();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		mMapView.onResume();
	}

	// 第三方插件初始化
	private void initView() {
		expandTabView = (ExpandTabView) findViewById(R.id.expandtab_view);
		viewMiddle = new ViewMiddle(this);
		viewRight = new ViewRight(this);
	}

	// 将网络数据放到第三方插件上
	private void initVaule() {
		// mViewArray.add(viewLeft);
		mViewArray.add(viewMiddle);
		mViewArray.add(viewRight);
		ArrayList<String> mTextArray = new ArrayList<String>();
		mTextArray.add("类别");
		mTextArray.add("附近");
		expandTabView.setValue(mTextArray, mViewArray);

	}

	// 第三方插件点击事件
	private void initListener() {

		viewMiddle.setOnSelectListener(new ViewMiddle.OnSelectListener() {

			@Override
			public void getValue(String showText) {

				onRefresh(viewMiddle, showText);

			}
		});

		viewRight.setOnSelectListener(new ViewRight.OnSelectListener() {
			@Override
			public void getValue(String showText) {
				allshowText = showText;
				thread(onRefresh(viewRight, showText));
			}
		});
	}

	private int getPositon(View tView) {
		for (int i = 0; i < mViewArray.size(); i++) {
			if (mViewArray.get(i) == tView) {
				return i;
			}
		}
		return -1;
	}

	private String onRefresh(View view, String showText) {

		expandTabView.onPressBack();
		int position = getPositon(view);
		if (position >= 0 && !expandTabView.getTitle(position).equals(showText)) {
			expandTabView.setTitle(showText, position);

		}
		return showText;
	}

	// 筛选
	private void thread(final String showtext) {
		title.clear();
		String type = "http://www2.huobi3j.com/keyword/getkeyword?name="
				+ showtext;
		abhttputil.get(type, new AbStringHttpResponseListener() {

			@Override
			public void onStart() {
				// TODO Auto-generated method stub
			}

			@Override
			public void onFinish() {
				// TODO Auto-generated method stub

			}

			@Override
			public void onFailure(int arg0, String arg1, Throwable arg2) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onSuccess(int arg0, String arg1) {
				// TODO Auto-generated method stub
				try {
					JSONObject object = new JSONObject(arg1);
					kid = object.getString("KID");
					newthread(kid, distant);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	public void showmenu(View v) {

		PopupMenu popup = new PopupMenu(this, v);
		popup.getMenuInflater().inflate(R.menu.menu, popup.getMenu());
		popup.show(); // showing popup menu
	}

	// 主页面点击事件
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.map:
			expandTabView.onPressBack();
			findViewById(R.id.list1).setVisibility(View.INVISIBLE);
			findViewById(R.id.bmapView).setVisibility(View.VISIBLE);

			break;
		case R.id.list:
			// initVaule();
			findViewById(R.id.bmapView).setVisibility(View.GONE);
			findViewById(R.id.list1).setVisibility(View.VISIBLE);

			break;
		case R.id.exit:
			AlertDialog.Builder builder = new AlertDialog.Builder(
					MainActivity.this);

			builder.setTitle("提示");
			builder.setMessage("是否退出本应用？");
			builder.setPositiveButton("确定",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							dialog.dismiss();

							finish();
							System.exit(0);
						}

					});
			builder.setNegativeButton("取消",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							dialog.dismiss();

						}
					});
			builder.create().show();
			break;
		case R.id.person:
			if (v.getId() == R.id.person) {
				popMenu.showAsDropDown(v);
			}
			break;
		case R.id.distance:
			count++;
			if (count == 1) {
				findViewById(R.id.meters).setVisibility(View.VISIBLE);
				wubaimi.setImageResource(R.drawable.yuandian);
				erbaimi.setImageResource(R.drawable.a);
				qianmi.setImageResource(R.drawable.a);
				erqianmi.setImageResource(R.drawable.a);
				wuqianmi.setImageResource(R.drawable.a);
				wanmi.setImageResource(R.drawable.a);

			} else {
				if (count % 2 == 1) {
					findViewById(R.id.meters).setVisibility(View.VISIBLE);

				} else {
					findViewById(R.id.meters).setVisibility(View.GONE);
				}

			}

			break;
		case R.id.wubaimi:
			wubaimi.setImageResource(R.drawable.yuandian);
			erbaimi.setImageResource(R.drawable.a);
			qianmi.setImageResource(R.drawable.a);
			erqianmi.setImageResource(R.drawable.a);
			wuqianmi.setImageResource(R.drawable.a);
			wanmi.setImageResource(R.drawable.a);
			distant = "500";
			newthread(kid, distant);
			break;
		case R.id.erbaimi:
			wubaimi.setImageResource(R.drawable.a);
			erbaimi.setImageResource(R.drawable.yuandian);
			qianmi.setImageResource(R.drawable.a);
			erqianmi.setImageResource(R.drawable.a);
			wuqianmi.setImageResource(R.drawable.a);
			wanmi.setImageResource(R.drawable.a);
			distant = "200";
			newthread(kid, distant);

			break;
		case R.id.qianmi:
			wubaimi.setImageResource(R.drawable.a);
			erbaimi.setImageResource(R.drawable.a);
			qianmi.setImageResource(R.drawable.yuandian);
			erqianmi.setImageResource(R.drawable.a);
			wuqianmi.setImageResource(R.drawable.a);
			wanmi.setImageResource(R.drawable.a);
			distant = "1000";
			newthread(kid, distant);

			break;
		case R.id.erqianmi:
			wubaimi.setImageResource(R.drawable.a);
			erbaimi.setImageResource(R.drawable.a);
			qianmi.setImageResource(R.drawable.a);
			erqianmi.setImageResource(R.drawable.yuandian);
			wuqianmi.setImageResource(R.drawable.a);
			wanmi.setImageResource(R.drawable.a);
			distant = "2000";
			newthread(kid, distant);

			break;
		case R.id.wuqianmi:
			wubaimi.setImageResource(R.drawable.a);
			erbaimi.setImageResource(R.drawable.a);
			qianmi.setImageResource(R.drawable.a);
			erqianmi.setImageResource(R.drawable.a);
			wuqianmi.setImageResource(R.drawable.yuandian);
			wanmi.setImageResource(R.drawable.a);
			distant = "5000";
			newthread(kid, distant);

			break;
		case R.id.yiwanmi:
			wubaimi.setImageResource(R.drawable.a);
			erbaimi.setImageResource(R.drawable.a);
			qianmi.setImageResource(R.drawable.a);
			erqianmi.setImageResource(R.drawable.a);
			wuqianmi.setImageResource(R.drawable.a);
			wanmi.setImageResource(R.drawable.yuandian);
			distant = "10000";
			newthread(kid, distant);
			break;
		default:
			break;
		}
	}

	// 个人中心点击事件
	@Override
	public void onItemClick(int index) {
		// TODO Auto-generated method stub
		switch (index) {
		case 0:
			Toast.makeText(this, "二维码", Toast.LENGTH_SHORT).show();
			break;
		case 1:
			Toast.makeText(this, "我的资料", Toast.LENGTH_SHORT).show();
			break;
		case 2:
			Toast.makeText(this, "商家代金券", Toast.LENGTH_SHORT).show();
			break;
		case 3:
			Toast.makeText(this, "货比三家代金券", Toast.LENGTH_SHORT).show();
			break;
		case 4:
			Intent i = new Intent(MainActivity.this, LogonActivity.class);
			startActivity(i);
			break;

		default:
			break;
		}
	}

	// 下拉刷新
	@Override
	public void onFooterLoad(AbPullToRefreshView arg0) {
		// TODO Auto-generated method stub
		pageindex = (page++) + "";
		getfoot();
	}

	// 上拉刷新
	@Override
	public void onHeaderRefresh(AbPullToRefreshView arg0) {
		// TODO Auto-generated method stub
		title.clear();
		newthread(kid, distant);
		refreshview.onHeaderRefreshFinish();
	}

	// 下拉刷新获得数据
	private void getfoot() {
		String Url = "http://www.huobi3j.com/product/searchproduct?kid=" + kid
				+ "&lat=23.01867&lng=113.13816&radius=" + distant
				+ "&sort=Price&typeid=&priceid=&sizeid=&pageindex=" + pageindex
				+ "%22";

		abhttputil.get(Url, new AbStringHttpResponseListener() {

			@Override
			public void onStart() {
				// TODO Auto-generated method stub
			}

			@Override
			public void onFinish() {
				// TODO Auto-generated method stub
			}

			@Override
			public void onFailure(int arg0, String arg1, Throwable arg2) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onSuccess(int arg0, String arg1) {

				ArrayList<Listitem> list = new ArrayList<Listitem>();
				// TODO Auto-generated method stub
				try {
					JSONObject object = new JSONObject(arg1);
					String contents = object.getString("contents");
					JSONArray array = new JSONArray(contents);

					for (int i = 0; i < array.length(); i++) {
						Listitem item = new Listitem();
						JSONObject detail = (JSONObject) array.get(i);
						String Name = detail.getString("title");
						String tags = detail.getString("tags");
						String Phone = detail.getString("Phone");
						String Price = detail.getString("Price");
						// String Address = detail.getString("address");
						String distance = detail.getString("distance");
						String loc = detail.getString("location");
						item.setName(Name);
						item.setPrices(Price);
						item.setPhone(Phone);
						item.setDistance(distance);
						item.setTags(tags);
						item.setLocation(loc);
						list.add(item);
					}
					title.addAll(list);
					adapter.notifyDataSetChanged();
					mDialogFragment.loadFinish();
					refreshview.onFooterLoadFinish();

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		});
	}
}
